// record.vue 的方法集合文件
// 用于提高代码可读性和维护性

import { dateHelperApi } from "@/pages/smart/utils/date-helper";
import { PlanBsApi } from "@/api/pp";
import { CsRecordStockRealApi } from "@/api/bs/csrecordstockreal";
import { CsRecordCostApi } from "@/api/bs/csrecordcost";
import { CsRecordApi } from "@/api/bs/csrecord";
import { BatchSplitApi } from "@/api/bs/batchsplit";
import { ProdChangeRecordApi } from "@/api/bs/prodchangerecord";
import { ScrapStockInApi } from "@/api/warehouse/scrapstockin";

export const recordMethods = {
  // 切换记录标签页
  async handleRecordTabChange(tabType) {
    this.recordActiveTab = tabType;
    
    // 根据标签类型加载对应的记录数据
    try {
      this.loading = true;
      
      switch (tabType) {
        case 'feeding':
          await this.loadFeedingRecords();
          break;
        case 'offline':
          await this.loadOfflineRecords();
          break;
        case 'scrap':
          await this.loadScrapRecords();
          break;
        default:
          console.warn('未知的记录类型:', tabType);
      }
    } catch (error) {
      console.error('加载记录数据失败:', error);
      uni.showToast({
        title: '加载记录数据失败',
        icon: 'error'
      });
    } finally {
      this.loading = false;
    }
  },

  
  // 加载上料记录
  async loadFeedingRecords() {
    try {
      const params = {
        pageNo: 1,
        pageSize: 10,
        processName: this.formData.processName,
        ywDate: [this.formData.currentDate + ' 00:00:00', this.formData.currentDate + ' 23:59:59'],
        creator: this.$store.state.user.nickname || this.$store.state.user.username,
        recordType: '上料出库' // 上料操作类型
      };
      
      const response = await CsRecordApi.getCsRecordPage(params);
      
      if (response.code === 0 && response.data && response.data.list) {
        this.feedingRecords = response.data.list;
      } else {
        this.feedingRecords = [];
      }
    } catch (error) {
      console.error('加载上料记录失败:', error);
      this.feedingRecords = [];
      throw error;
    }
  },

  // 加载下线记录
  async loadOfflineRecords() {
    try {
      const params = {
        pageNo: 1,
        pageSize: 10,
        processName: this.formData.processName,
        ywDate: [this.formData.currentDate + ' 00:00:00', this.formData.currentDate + ' 23:59:59'],
        creator: this.$store.state.user.nickname || this.$store.state.user.username,
        recordType: '下线入库' // 下线操作类型
      };
      
      const response = await CsRecordApi.getCsRecordPage(params);
      
      if (response.code === 0 && response.data && response.data.list) {
        this.offlineRecords = response.data.list;
      } else {
        this.offlineRecords = [];
      }
    } catch (error) {
      console.error('加载下线记录失败:', error);
      this.offlineRecords = [];
      throw error;
    }
  },

  // 加载报废记录
  async loadScrapRecords() {
    try {
      const params = {
        pageNo: 1,
        pageSize: 10,
        processName: this.formData.processName,
        ywDate: [this.formData.currentDate + ' 00:00:00', this.formData.currentDate + ' 23:59:59'],
        creator: this.$store.state.user.nickname || this.$store.state.user.username,
        recordType: '报废入库' // 报废操作类型（注意：后端若无此类型将查询为空）
      };
      
      const response = await CsRecordApi.getCsRecordPage(params);
      
      if (response.code === 0 && response.data && response.data.list) {
        this.scrapRecords = response.data.list;
      } else {
        this.scrapRecords = [];
      }
    } catch (error) {
      console.error('加载报废记录失败:', error);
      this.scrapRecords = [];
      throw error;
    }
  },



  // PDA自带热敏打印功能，简化实现
  async printWithPDA(imagePath) {
    try {
      console.log('开始PDA热敏打印...')
      
      if (typeof plus !== 'undefined' && plus.android) {
        // 方案1: 使用PDA原生printImage接口
        if (plus.device && plus.device.printImage) {
          plus.device.printImage(imagePath, {
            width: 384,
            align: 'center',
            autoCut: true,
            copies: 1
          })
          console.log('PDA原生打印接口调用成功')
          return
        }
        
        // 方案2: 使用Android Intent调用系统打印
        const Intent = plus.android.importClass('android.content.Intent')
        const Uri = plus.android.importClass('android.net.Uri')
        const File = plus.android.importClass('java.io.File')
        
        try {
          const imageFile = new File(imagePath)
          const imageUri = Uri.fromFile(imageFile)
          const printIntent = new Intent('android.intent.action.PRINT')
          printIntent.setDataAndType(imageUri, 'image/*')
          printIntent.putExtra('scaleType', 'fit')
          
          plus.android.runtimeMainActivity().startActivity(printIntent)
          console.log('PDA Intent打印调用成功')
          
        } finally {
          plus.android.deleteObject(Intent)
          plus.android.deleteObject(Uri)
          plus.android.deleteObject(File)
        }
      } else {
        console.log('非PDA环境，跳过打印')
      }
      
    } catch (error) {
      console.error('PDA打印失败:', error)
      console.log('PDA打印功能调用完成（部分功能可能需要手动确认）')
    }
  },



  // 初始化数据
  async initData() {
    try {
      // 加载数据源
      await this.loadDataSources();

      // 初始化三种记录类型的模拟数据
      this.initRecordData();
    } catch (error) {
      console.error("初始化数据失败:", error);
      uni.showToast({
        title: "初始化失败",
        icon: "error",
      });
    }
  },

  // 切换出库类型
  switchOutType(type) {
    this.formData.outType = type;
    this.resetSearch();
    this.selectedRows = [];
    this.selectedTable = [];
  },

  // 选择行
  selectRow(index) {
    const rowIndex = this.selectedRows.indexOf(index);
    if (rowIndex > -1) {
      this.selectedRows.splice(rowIndex, 1);
    } else {
      this.selectedRows.push(index);
    }
  },

  // 处理日期变更
  handleDateChange(e) {
    this.formData.currentDate = e.detail.value;
  },

  // 处理炉批选择
  handleDayBillChange(e) {
    const idx = e.detail.value;
    this.planNoIndex = idx;
    if (this.dayBills[idx]) {
      this.formData.furnaceNo = this.dayBills[idx].billNo;
    }
  },

  /* 时间选择处理 */
  handleTimeChange(timeFilter) {
    console.log('时间选择变更:', timeFilter, '当前时间范围:', this.timeRange);
    this.timeFilter = timeFilter;
    
    try {
      // 使用通用的updateDateRange函数，直接获取返回值
      const { startDate, endDate } = dateHelperApi.updateDateRange(timeFilter);
      console.log('获取到时间范围:', startDate, '-', endDate);
      
      // 更新时间范围
      this.timeRange = {
        startTime: startDate,
        endTime: endDate,
      };
      
      console.log('更新时间范围成功:', this.timeRange);
      
      // 时间范围更新完成后，重新加载日账单
      this.loadDayBill();
    } catch (error) {
      console.error('时间选择处理失败:', error);
      uni.showToast({
        title: '时间选择失败',
        icon: 'error'
      });
    }
  },

  // 处理计划日期变更
  handlePlanDateChange(e) {
    if (this.currentPlanItem) {
      this.$set(this.currentPlanItem, "planDate", e.detail.value);
    }
  },

  // 处理标准选择
  handleStandardChange(e) {
    if (this.currentPlanItem && this.standards.length > 0) {
      const selectedIndex = e.detail.value;
      this.$set(this.currentPlanItem, "standIndex", selectedIndex);
      this.$set(
        this.currentPlanItem,
        "standNo",
        this.standards[selectedIndex]
      );
    }
  },

  // 处理钢种选择
  handleSteelGradeChange(e) {
    if (this.currentPlanItem && this.steelGrades.length > 0) {
      const selectedIndex = e.detail.value;
      this.$set(this.currentPlanItem, "steelGradeIndex", selectedIndex);
      this.$set(
        this.currentPlanItem,
        "steelGradeName",
        this.steelGrades[selectedIndex]
      );
    }
  },

  // 处理规格选择
  handleSpecChange(e) {
    if (this.currentPlanItem && this.specs.length > 0) {
      const selectedIndex = e.detail.value;
      this.$set(this.currentPlanItem, "specIndex", selectedIndex);
      this.$set(this.currentPlanItem, "prodSpec", this.specs[selectedIndex]);
    }
  },

  // 处理机组输入确认
  handleProdCenterConfirm() {
    // 机组输入确认后的处理逻辑
    console.log("机组输入确认:", this.formData.prodCenter);
    // 这里可以添加验证逻辑或其他处理
  },

  // 聚焦到机组输入框
  focusProdCenterInput() {
    // 使用v-bind:focus来控制聚焦状态
    this.prodCenterFocus = false;
    this.$nextTick(() => {
      this.prodCenterFocus = true;
    });
  },

  // 提交当前计划
  submitCurrentPlan() {
    // 先同步数据到selectedTable
    if (!this.syncCurrentPlanToTable()) {
      return;
    }

    const item = this.currentPlanItem;

    // 验证必填项
    if (!item.planDate) {
      uni.showToast({
        title: "请选择计划日期",
        icon: "none",
      });
      return;
    }

    if (
      item.ProdCount === null ||
      item.ProdCount === undefined ||
      item.ProdCount === "" ||
      item.TransCount === null ||
      item.TransCount === undefined ||
      item.TransCount === ""
    ) {
      uni.showToast({
        title: "请填写完整的计划量",
        icon: "none",
      });
      return;
    }

    // 验证数字有效性
    if (isNaN(Number(item.ProdCount)) || isNaN(Number(item.TransCount))) {
      uni.showToast({
        title: "计划量格式错误",
        icon: "none",
      });
      return;
    }

    // 调用原有的提交方法
    this.submitOutOrder();
  },

  // 重置当前计划
  resetCurrentPlan() {
    const item = this.currentPlanItem;
    if (item) {
      this.$set(item, "planDate", new Date(this.formData.currentDate + "T00:00:00").toISOString());
      this.$set(item, "standNo", "");
      this.$set(item, "steelGradeName", "");
      this.$set(item, "prodSpec", "");
      this.$set(item, "ProdCount", 0);
      this.$set(item, "TransCount", 0);
      this.$set(item, "standIndex", -1);
      this.$set(item, "steelGradeIndex", -1);
      this.$set(item, "specIndex", -1);
    }
  },

  // 导航计划
  navigatePlan(direction) {
    const newIndex = this.currentPlanIndex + direction;
    if (newIndex >= 0 && newIndex < this.selectedTable.length) {
      this.currentPlanIndex = newIndex;
    }
  },

  // 加载标准数据（预留方法）
  async loadStandards() {
    // TODO: 调用API获取标准数据
    this.standards = await api.getStandards();
    // 临时模拟数据用于测试
    //this.standards = ["GB/T 700", "GB/T 1591", "GB/T 3077", "GB/T 4171"];
  },

  // 加载钢种数据（预留方法）
  async loadSteelGrades() {
    // TODO: 调用API获取钢种数据
    this.steelGrades = await api.getSteelGrades();
    // 临时模拟数据用于测试
    //this.steelGrades = ["Q235", "Q345", "Q390", "Q420", "Q460"];
  },

  // 加载规格数据（预留方法）
  async loadSpecs() {
    // TODO: 调用API获取规格数据
    this.specs = await api.getSpecs();
    // 临时模拟数据用于测试
    //this.specs = ["Φ12", "Φ14", "Φ16", "Φ18", "Φ20", "Φ22", "Φ25"];
  },

  // 加载所有数据源
  async loadDataSources() {
    try {
      console.log('开始加载数据源...');
      // 并行加载所有数据源（不包括loadDayBill，因为它已经在handleTimeChange中调用）
      await Promise.all([
        this.loadStandards(),
        this.loadSteelGrades(),
        this.loadSpecs(),
        // this.loadDayBill(), // 注释掉：已经在handleTimeChange中调用
      ]);
      console.log('数据源加载完成');
    } catch (error) {
      console.error("加载数据源失败:", error);
    }
  },

  // 加载炉次日账单
  async loadDayBill() {
    console.log('开始加载炉次日账单，当前时间范围:', this.timeRange);
    console.log('当前工艺名称:', this.formData.processName);
    
    // 构建查询参数
    const params = {
      processName: this.formData.processName,
      pageNo: 1,
      pageSize: 100,
    };
    
    // 只有在时间范围有效时才添加时间参数
    if (this.timeRange.startTime && this.timeRange.endTime) {
      params.ywDate = [this.timeRange.startTime, this.timeRange.endTime];
      console.log('添加时间参数:', params.ywDate);
    } else {
      console.warn('时间范围无效，不添加时间参数');
    }
    
    try {
      console.log('调用PlanBsApi.getPlanBsPage，参数:', params);
      // TODO: 换成真实 API，这里用 mock 数据演示
      const res = await PlanBsApi.getPlanBsPage(params);

      console.log('PlanBsApi返回结果:', res);
      
      if (res.code === 0) {
        console.log("加载作业计划成功:", res.data.list);
        this.dayBills = res.data.list || [];
        console.log("更新dayBills:", this.dayBills.length, "条记录");
      } else {
        console.warn("加载作业计划返回非0状态码:", res.code, res.msg);
        this.dayBills = [];
      }
    } catch (err) {
      console.error("加载作业计划失败:", err);
      this.dayBills = [];
    }
  },

  // 批号模糊查询方法（已废弃 - 改为弹窗查询）
  async queryBatchBo(keyword) {
    // 此方法已废弃，批号查询改为弹窗方式
    console.log("批号模糊查询方法已废弃，使用弹窗查询方式");
    return [];
  },

  // 显示批号查询弹窗
  showBatchQueryModal() {
    this.showBatchQueryDialog = true;
    this.batchQueryKeyword = this.formData.batchNo;
    this.batchSearchResults = [];
    
    // 如果当前批号输入框有值，自动执行查询
    if (this.batchQueryKeyword && this.batchQueryKeyword.trim().length >= 2) {
      this.$nextTick(() => {
        this.executeBatchQuery();
      });
    }
  },

  // 关闭批号查询弹窗
  closeBatchQueryModal() {
    this.showBatchQueryDialog = false;
    this.batchQueryKeyword = "";
    this.batchSearchResults = [];
    this.batchQueryLoading = false;
  },

  // 批号输入框confirm事件 - 查询并自动赋值第一行数据
  async handleBatchNoConfirm() {
    const batchNo = this.formData.batchNo?.trim();
    if (!batchNo || batchNo.length < 2) {
      uni.showToast({
        title: "请输入至少2个字符的批号",
        icon: "none"
      });
      return;
    }

    try {
      // 使用批号作为查询关键字
      this.batchQueryKeyword = batchNo;
      
      // 执行查询
      const response = await CsRecordStockRealApi.getCsRecordStockRealPage({
        batchNo: batchNo,
        pageNum: 1,
        pageSize: 50
      });

      if (response.code === 0 && response.data) {
        const records = response.data.records || response.data.list || response.data || [];
        this.batchSearchResults = records.map(item => ({
          batchNo: item.batchNo || '',
          furnaceNo: item.furnaceNo || '',
          steelGradeName: item.steelGradeName || '',
          prodSpec: item.prodSpec || '',
          weight: item.qmAmount || 0
        }));
        
        if (this.batchSearchResults.length === 0) {
          uni.showToast({
            title: "未查询到相关批号",
            icon: "none"
          });
          return;
        }
        
        // 如果有查询结果，自动选择第一行数据
        if (this.batchSearchResults.length > 0) {
          const firstItem = this.batchSearchResults[0];
          
          // 判断钢种是否与页面的钢种相等
          if (this.formData.steelGradeName && firstItem.steelGradeName !== this.formData.steelGradeName) {
            // 显示确认提示
            uni.showModal({
              title: "钢种不一致提示",
              content: `与计划钢种不一致，是否按照实际投料？\n计划钢种：${this.formData.steelGradeName}\n实际钢种：${firstItem.steelGradeName}`,
              confirmText: "确认",
              cancelText: "取消",
              success: (res) => {
                if (res.confirm) {
                  // 用户确认后赋值
                  this.assignBatchItem(firstItem);
                }
                // 用户取消则不做任何操作
              }
            });
          } else {
            // 钢种一致或页面没有钢种，直接赋值
            this.assignBatchItem(firstItem);
          }
        }
      } else {
        uni.showToast({
          title: response.msg || "查询失败",
          icon: "error"
        });
        this.batchSearchResults = [];
      }
    } catch (error) {
      console.error("批号查询失败:", error);
      uni.showToast({
        title: "查询失败，请重试",
        icon: "error"
      });
      this.batchSearchResults = [];
    }
  },

  // 执行批号查询
  async executeBatchQuery() {
    if (!this.batchQueryKeyword || this.batchQueryKeyword.trim().length < 2) {
      uni.showToast({
        title: "请输入至少2个字符进行查询",
        icon: "none"
      });
      return;
    }

    this.batchQueryLoading = true;
    try {
      // 使用真实API调用CsRecordStockRealApi.getCsRecordStockRealPage
      const response = await CsRecordStockRealApi.getCsRecordStockRealPage({
        batchNo: this.batchQueryKeyword.trim(),
        pageNum: 1,
        pageSize: 50
      });

      if (response.code === 0 && response.data) {
        // 将API返回的数据转换为需要的格式
        const records = response.data.records || response.data.list || response.data || [];
        this.batchSearchResults = records.map(item => ({
          batchNo: item.batchNo || '',
          furnaceNo: item.furnaceNo || '',
          steelGradeName: item.steelGradeName || '',
          prodSpec: item.prodSpec || '',
          weight: item.qmAmount || 0
        }));
        
        if (this.batchSearchResults.length === 0) {
          uni.showToast({
            title: "未查询到相关批号",
            icon: "none"
          });
        }
      } else {
        uni.showToast({
          title: response.msg || "查询失败",
          icon: "error"
        });
        this.batchSearchResults = [];
      }
    } catch (error) {
      console.error("批号查询失败:", error);
      uni.showToast({
        title: "查询失败，请重试",
        icon: "error"
      });
      this.batchSearchResults = [];
    } finally {
      this.batchQueryLoading = false;
    }
  },

  // 选择批号并关闭弹窗
  selectBatchItem(item) {
    // 判断钢种是否与页面的钢种相等
    if (this.formData.steelGradeName && item.steelGradeName !== this.formData.steelGradeName) {
      // 先关闭批号查询弹框，避免遮挡确认对话框
      this.closeBatchQueryModal();
      
      // 延迟显示确认提示，确保弹框完全关闭
      setTimeout(() => {
        uni.showModal({
          title: "钢种不一致提示",
          content: `与计划钢种不一致，是否按照实际投料？\n计划钢种：${this.formData.steelGradeName}\n实际钢种：${item.steelGradeName}`,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            if (res.confirm) {
              // 用户确认后赋值
              this.assignBatchItem(item);
            }
            // 用户取消则不做任何操作
          }
        });
      }, 300); // 300ms延迟，确保动画完成
    } else {
      // 钢种一致或页面没有钢种，直接赋值
      this.assignBatchItem(item);
    }
  },

  // 赋值批号信息
  assignBatchItem(item) {
    // 将选中的批号信息赋值到表单
    this.formData.batchNo = item.batchNo;
    this.formData.steelGradeName = item.steelGradeName;
    this.formData.furnaceNo = item.furnaceNo;
    this.formData.prodSpec = item.prodSpec;
    // 将重量赋值到上料重量字段
    this.formData.prodCountOn = item.weight || 0;
    
    // 关闭弹窗
    this.closeBatchQueryModal();
    
    uni.showToast({
      title: "批号选择成功",
      icon: "success"
    });
  },

  // 拆批功能
  async splitBatch() {
    console.log("拆批功能被调用");
    console.log("当前批次号:", this.formData.batchNo);
    
    // 1. 判断批次输入框是否有值
    if (!this.formData.batchNo || this.formData.batchNo.trim() === '') {
      uni.showToast({
        title: "请扫码批次",
        icon: "none"
      });
      return;
    }
    
    console.log("批次号验证通过，继续执行拆批逻辑");

    try {
      // 2. 设置查询关键字为当前批次号
      this.batchQueryKeyword = this.formData.batchNo.trim();
      
      // 3. 执行批次查询
      await this.executeBatchQuery();
      
      // 4. 等待查询完成后处理结果
      if (this.batchSearchResults.length > 0) {
        // 获取当前批次号
        const currentBatchNo = this.formData.batchNo.trim();
        
        // 提取基础批次号（去除序号部分）
        let baseBatchNo = currentBatchNo;
        
        if (currentBatchNo.includes('-')) {
          const parts = currentBatchNo.split('-');
          baseBatchNo = parts[0]; // 基础批次号部分
        }
        
        // 循环遍历批次结果表，找到最大的序号
        let maxNumber = 0;
        let hasBaseBatch = false; // 是否存在基础批次号
        
        this.batchSearchResults.forEach(item => {
          const batchNo = item.batchNo || '';
          
          if (batchNo === baseBatchNo) {
            // 存在基础批次号（如ABC），视为序号0
            hasBaseBatch = true;
            maxNumber = Math.max(maxNumber, 0);
          } else if (batchNo.startsWith(baseBatchNo + '-')) {
            const parts = batchNo.split('-');
            if (parts.length === 2) {
              const num = parseInt(parts[1]) || 0;
              maxNumber = Math.max(maxNumber, num);
            }
          }
        });
        
        // 生成新的批次号：始终取最大序号+1
        const newBatchNo = `${baseBatchNo}-${maxNumber + 1}`;
        
        // 更新批次输入框
        this.formData.batchNo = newBatchNo;
        
        uni.showToast({
          title: `拆批成功：${newBatchNo}`,
          icon: "success"
        });
      } else {
        // 查询无结果，提示用户
        uni.showToast({
          title: "未查询到该批次信息",
          icon: "none"
        });
      }
    } catch (error) {
      console.error("拆批失败:", error);
      uni.showToast({
        title: "拆批失败，请重试",
        icon: "error"
      });
    }
  }, 

  // 重置搜索
  resetSearch() {
    this.searchForm = {
      materialCode: "",
      materialName: "",
      customerName: "",
    };
    this.currentTable = [];
    this.selectedRows = [];
  },

  // 数字验证
  validateNumber(event, item, field) {
    const value = Number(item[field]);
    if (isNaN(value) || value <= 0) {
      uni.showToast({
        title: "请输入有效的数字",
        icon: "none",
      });
      item[field] = 0;
    } else if (value > 999999) {
      uni.showToast({
        title: "数字不能超过999999",
        icon: "none",
      });
      item[field] = 999999;
    }
  },

  // 存储计划选中信息
  storePlanInfo(item) {
    // 存储计划选中信息（带新字段）
    this.selectedTable.push({
      ...item,
    });
    // 自动切换到计划编制标签页
    this.activeTab = "selected";
    
    // 将计划的planNo、steelGradeName、prodSpec赋值到相应的表单字段
    this.formData.planNo = item.planNo || '';
    this.formData.steelGradeName = item.steelGradeName || '';
    this.formData.prodSpec = item.prodSpec || '';
    
    // 延迟聚焦到批次号输入框，等待DOM更新完成
    this.$nextTick(() => {
      this.batchNoFocus = false;
      this.$nextTick(() => {
        this.batchNoFocus = true;
      });
    });
  },

  // 上料提交
  async submitOnline() {
    console.log("上料提交被调用");
    if (!this.canSubmitOnline) {
      uni.showToast({
        title: "请完善上料信息",
        icon: "none",
      });
      return;
    }

    try {
      // 构建上料数据
      const onlineData = {
        planNo: this.formData.planNo, // 计划号
        batchNo: this.formData.batchNo,
        steelGradeName: this.formData.steelGradeName,
        prodSpec: this.formData.prodSpec,
        qmAmount: Number(this.formData.prodCountOn), // 上料重量
        furnaceNo: this.formData.furnaceNo,
        ywDate: new Date(this.formData.currentDate + "T00:00:00").getTime(),
        createTime: new Date().toISOString(),
        processName: this.formData.processName || "",
        prodCenter: this.formData.prodCenter || "",
        workShift: this.$store.state.user.userConfig?.workShift || "",
        wortkType: this.$store.state.user.userConfig?.workClass || "",
        creator: this.$store.state.user.nickname || this.$store.state.user.username || "",
        recordMemo: this.formData.remark || "",
        recordType: "上料出库",
        reserveVarchar1:"粗丝",
      };

      // 显示确认对话框
      const confirmed = await this.showSubmitConfirm(onlineData, "上料");
      if (!confirmed) return;

      this.loading = true;

      // TODO: 调用实际上料API
      const response = await CsRecordApi.createCsRecord(onlineData);

      if (response.code === 0) {
        await this.handleSubmitSuccess(response, "上料");

        // 重新加载上料记录
        await this.loadFeedingRecords();

      } else {
        uni.showToast({
          title: response.msg || "上料失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("上料提交失败:", error);
      uni.showToast({
        title: "上料提交失败",
        icon: "error",
      });
    } finally {
      this.loading = false;
    }
  },

  // 下线提交
  async submitOffline() {
    if (!this.canSubmitOffline) {
      uni.showToast({
        title: "请完善下线信息",
        icon: "none",
      });
      return;
    }

    try {
      // 构建下线数据
      const offlineData = {
         planNo: this.formData.planNo, // 计划号
        batchNo: this.formData.batchNo,
        steelGradeName: this.formData.steelGradeName,
        prodSpec: this.formData.prodSpec,
        qmAmount: Number(this.formData.qmAmount), // 下线重量
        furnaceNo: this.formData.furnaceNo,
        ywDate: new Date(this.formData.currentDate + "T00:00:00").getTime(),
        createTime: new Date().toISOString(),
        processName: this.formData.processName || "",
        prodCenter: this.formData.prodCenter || "",
        workShift: this.$store.state.user.userConfig?.workShift || "",
        wortkType: this.$store.state.user.userConfig?.workClass || "",
        creator: this.$store.state.user.nickname || this.$store.state.user.username || "",
        recordMemo: this.formData.remark || "",
        recordType: "下线入库",
        reserveVarchar1:  "粗丝",
      };

      // 显示确认对话框
      const confirmed = await this.showSubmitConfirm(offlineData, "下线");
      if (!confirmed) return;

      this.loading = true;

      // TODO: 调用实际下线API
      const response = await CsRecordApi.createCsRecord(offlineData);

      if (response.code === 0) {
        await this.handleSubmitSuccess(response, "下线");
      } else {
        uni.showToast({
          title: response.msg || "下线失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("下线提交失败:", error);
      uni.showToast({
        title: "下线提交失败",
        icon: "error",
      });
    } finally {
      this.loading = false;
    }
  },

  // 废品报废提交
  async submitScrap() {
    if (!this.canSubmitScrap) {
      uni.showToast({
        title: "请完善报废信息",
        icon: "none",
      });
      return;
    }

    try {
      // 构建报废数据
      const scrapData = {
         warehouseCode: "原料库",
         warehouseName: "原料库",
         mateialCode: "MAT999", // 注意：后端VO类拼写为mateialCode
         mateialName: "特殊废钢", // 注意：后端VO类拼写为mateialName
        batchNo: this.formData.batchNo,
        steelGradeName: this.formData.steelGradeName,
        prodSpec: this.formData.prodSpec,
        scrapWg: Number(this.formData.scrapWeight), // 使用正确的重量字段名
        wgEquipCode: this.formData.wgEquipCodeScrape || "",
        furnaceNo: this.formData.furnaceNo,
        ywDate: new Date(this.formData.currentDate + "T00:00:00").getTime(),
        processName: this.formData.processName || "",
        prodCenter: this.formData.prodCenter || "",
        recordMemo: this.formData.remark || "",
        inType: "报废入库",
      };

      // 显示确认对话框
      const confirmed = await this.showSubmitConfirm(scrapData, "报废");
      if (!confirmed) return;

      this.loading = true;

      // TODO: 调用实际报废API
      const response = await ScrapStockInApi.createScrapStockIn(scrapData);

      

      if (response.code === 0) {
        await this.handleSubmitSuccess(response, "报废");
      } else {
        uni.showToast({
          title: response.msg || "报废失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("报废提交失败:", error);
      uni.showToast({
        title: "报废提交失败",
        icon: "error",
      });
    } finally {
      this.loading = false;
    }
  },

  // 获取重量
  getWeight() {
    try {
      // TODO: 调用称重API获取重量
      // const weight = await weightApi.getCurrentWeight();

      // 模拟称重数据
      const mockWeight = Math.round(Math.random() * 2000 + 100); // 100-2100kg随机重量

      // 根据当前操作类型设置相应字段
      if (this.activeTab === "feeding") {
        this.formData.qmAmount = mockWeight;
      } else if (this.activeTab === "offline") {
        this.formData.offlineWeight = mockWeight;
      } else if (this.activeTab === "scrap") {
        this.formData.scrapWeight = mockWeight;
      }

      uni.showToast({
        title: `称重成功：${mockWeight}kg`,
        icon: "success",
      });

      console.log("称重结果:", mockWeight);
    } catch (error) {
      console.error("称重失败:", error);
      uni.showToast({
        title: "称重失败，请重试",
        icon: "error",
      });
    }
  },

  // 扫码查询
  async searchByScan() {
    try {
      // TODO: 调用扫码API
      // const scanResult = await scanApi.scanBarcode();

      // 模拟扫码结果
      const mockScanResult = {
        code: 0,
        data: {
          batchNo: "S20250601" + Math.floor(Math.random() * 1000),
          steelGradeName: ["Q235", "Q345", "Q390"][
            Math.floor(Math.random() * 3)
          ],
          prodSpec: ["Φ12", "Φ14", "Φ16", "Φ18"][
            Math.floor(Math.random() * 4)
          ],
          weight: Math.round(Math.random() * 1500 + 500),
        },
      };

      if (mockScanResult.code === 0) {
        const data = mockScanResult.data;

        // 填充表单数据
        this.formData.batchNo = data.batchNo;
        this.formData.steelGradeName = data.steelGradeName;
        this.formData.prodSpec = data.prodSpec;

        // 根据当前操作类型设置重量
        if (this.activeTab === "feeding") {
          this.formData.qmAmount = data.weight;
        } else if (this.activeTab === "offline") {
          this.formData.offlineWeight = data.weight;
        } else if (this.activeTab === "scrap") {
          this.formData.scrapWeight = data.weight;
        }

        uni.showToast({
          title: "扫码成功",
          icon: "success",
        });

        console.log("扫码查询结果:", data);
      } else {
        uni.showToast({
          title: "扫码失败，请重试",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("扫码查询失败:", error);
      uni.showToast({
        title: "扫码查询失败",
        icon: "error",
      });
    }
  },

  // 扫描设备码
  async scanMachineCode() {
    // 清除当前机组内容
    this.formData.prodCenter = "";

    // 重新聚焦到机组输入框
    this.$nextTick(() => {
      this.focusProdCenterInput();
    });

    
  },

  // 重置表单
  resetForm() {
    // 保存当前机组、班次、班别信息
    const userConfig = this.$store.state.user.userConfig;
    const savedWorkInfo = {
      workShift: userConfig?.workShift || "",
      workClass: userConfig?.workClass || "",
      processName: userConfig?.processName || "",
      prodCenter: userConfig?.prodCenter || ""
    };
    
    this.formData = {
      currentDate: dateHelperApi.getCurrentDate(),
      outType: "",
      // 新增字段重置
      planNo: "", // 计划号
      batchNo: "",
      steelGradeName: "",
      furnaceNo: "",
      prodSpec: "",
      qmAmount: 0,
      prodCountOn: 0, // 上料重量
      offlineWeight: 0,
      scrapWeight: 0,
      scrapReason: "",
      // 保留机组、班次、班别信息
      workShift: savedWorkInfo.workShift,
      workClass: savedWorkInfo.workClass,
      processName: savedWorkInfo.processName,
      prodCenter: savedWorkInfo.prodCenter
    };
    this.searchForm = {
      materialCode: "",
      materialName: "",
      customerName: "",
    };
    this.timeFilter = "today"; // 重置时间筛选状态
    this.currentTable = [];
    this.selectedTable = [];
    this.selectedRows = [];
    this._tempPlanItem = null; // 重置临时计划项
    this.currentPlanIndex = 0; // 重置计划索引
  },

  

  // 显示提交确认（支持多种操作类型）
  showSubmitConfirm(submitData, operationType ) {
    return new Promise((resolve) => {
      let content = "";

        // 单个操作提交逻辑（上料/下线/报废）
        const { batchNo, steelGradeName, prodSpec, qmAmount,prodCountOn,scrapWg } = submitData;
        if(operationType === "上料"){
          content = `批次号：${batchNo}\n钢种：${steelGradeName} \n规格：${prodSpec}\n重量：${qmAmount}kg\n是否确认${operationType}？`;
        }else if(operationType === "下线"){
          content = `批次号：${batchNo}\n钢种：${steelGradeName} \n规格：${prodSpec}\n重量：${qmAmount}kg\n是否确认${operationType}？`;
        }else if(operationType === "报废"){
          content = `批次号：${batchNo}\n钢种：${steelGradeName} \n规格：${prodSpec}\n重量：${scrapWg}kg\n是否确认${operationType}？`;
        }

      uni.showModal({
        title: `确认${operationType}`,
        content: content,
        confirmText: "确认",
        cancelText: "取消",
        success: (res) => {
          resolve(res.confirm);
        },
      });
    });
  },

  // 处理提交成功
  async handleSubmitSuccess(response, operationType = "计划") {
    const messages = {
      计划: "出库单创建成功",
      上料: "上料成功",
      下线: "下线成功",
      报废: "报废成功",
    };

    uni.showToast({
      title: messages[operationType] || "操作成功",
      icon: "success",
      duration: 2000,
    });

    console.log(`${operationType}成功:`, response.data);

    // 只有计划提交才返回上一页，单个操作不返回
    if (operationType === "计划") {
      // 重置表单
      this.resetForm();

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 2000);
    }
  },

  // 同步当前计划到表格
  syncCurrentPlanToTable() {
    // 预留方法，用于同步计划数据
    return true;
  },

  // 提交出库单（预留方法）
  async submitOutOrder() {
    // 预留方法，用于提交出库单
    console.log("提交出库单");
  },

  // 初始化记录数据
  async initRecordData() {
    // 初始化三种记录类型的模拟数据
    this.feedingRecords = [];
    this.offlineRecords = [];
    this.scrapRecords = [];
    
    // 默认加载上料记录
    try {
      await this.loadFeedingRecords();
    } catch (error) {
      console.error('初始化加载上料记录失败:', error);
    }
  }
};